/**
 * @description 用户选择器
 */
var UserSelector = {
		
	/**
	 * @param {} callbackOrConf 回调函数或配置选项，若为map类型，则表示为配置选项
	 * @param {} isSingle 是否单选
	 * @param {} isForFlow 是否为工作流的配置选择
	 * @return {}
	 */
	getView : function(callbackOrConf,isSingle, selval,isForFlow,mobileFlag) {
		//单选
		if(typeof(callbackOrConf) == 'object'){
			this.scope = callbackOrConf.scope;
			this.callback = callbackOrConf.callback;
		} else {
			this.scope = this;
			this.callback = callbackOrConf;
		}
		this.isSingle=(isSingle!=null)?isSingle:true;
		this.mobileFlag=(mobileFlag!=null)?mobileFlag:false;
		var panel = this.initPanel(isSingle, selval);
		// window
		var window = new Ext.Window({
			id : 'UserSelectorWin',
			title : '选择用户',
			iconCls : 'menu-appuser',
			width : 800,
			minWidth : 800,
			height : 480,
			minHeight : 480,
			layout : 'fit',
			border : false,
			maximizable : true,
			modal : true,
			items : [panel],
			buttonAlign : 'center',
			buttons : [{
				text : '确认',
				iconCls : 'btn-ok',
				scope : this,
				handler : this.submit
			}, {
				text : '关闭',
				iconCls:'btn-cancel',
				scope : this,
				handler : this.close
			}]
		});
		
		if(isForFlow){
			window.addButton(new Ext.Button({
				text : '发起人',
				iconCls : 'menu-subuser',
				scope : this,
				handler : function(){
					this.callback.call(this, '__start', '[发起人]');
					window.close();
				}
			}));
		}
		
		return window;
	},

	/**
	 * 组件初始化
	 * @param isSingle 是否单选,默认单选
	 */
	initPanel : function(isSingle, selval) {
		////////////////////treePanel[left节点] start/////////////////////////////
		this.treePanel = Ext.create('Ext.ux.TreePanelEditor', {
			autoScroll : true,
			title : '按单位分类 ',
			iconCls : 'dep-user',
			showToolbar: false,
			useArrows: true,
			url : __ctxPath + '/system/listDepartment.do',
			root : {
				expanded : true
			},
			rootVisible : false,
			scope: this,
			onclick : this.clickNode
		});
		////////////////////treePanel[left节点] end/////////////////////////////

		///////////////////rolePanel start///////////////////////////
		this.rolePanel = Ext.create('Ext.ux.TreePanelEditor', {
			autoScroll : true,
			iconCls : 'role-user',
			title : '按角色分类 ',
			showToolbar: false,
			url : __ctxPath + '/system/treeAppRole.do',
			root : {
				expanded : true
			},
			rootVisible : false,
			scope: this,
			onclick : this.clickRoleNode
		});
		//////////////////////rolePanel end////////////////////////////
		
		//////////////////onlinePanel start////////////////////////////////
		this.onlinePanel = new Ext.Panel({
			autoScroll : true,
			iconCls : 'online-user',
			title : '在线人员  ',
			listeners : {
				scope: this,
				'expand' : this.clickOnlinePanel
			}
		});
		///////////////////onlinePanel end/////////////////////////////

		///////////////////contactGrid[用户列表] start///////////////////
		this.contactGrid = new KE.GridPanel({
			title : '用户列表',
			autoScroll : true,
			region : 'center',
			height : 380,
			width: 100,
			pageSize: 1000,
			showPaging: false,
			isShowTbar: false,
			singleSelect: isSingle,
			autoWidth:false,
			rownumbercfg: {
				width: 30
			},
			url : __ctxPath + '/system/selectAppUser.do',
			fields : ['userId', 'fullname', 'title', 'mobile'],
			defaults : {
				menuDisabled : true
			},
			columns : [{
						header : "姓名",
						dataIndex : 'fullname',
						width : 60,
						renderer:function(value, meta, record){
							var title=record.data.title;
							if(title=='1'){
								return '<img src="'+__ctxPath+'/images/flag/man.png"/>&nbsp;'+value;
							}else{
								return '<img src="'+__ctxPath+'/images/flag/women.png"/>&nbsp;'+value;
							}
						}
					}]
			
		}); 
		// 单选：根据传入值，选中GridPanel
		Ext.defer(function() {
			if(isSingle && selval) {
				var model = this.contactGrid.getSelectionModel();
				this.contactGrid.getStore().each(function(rec) {
					if(rec.data.userId == selval) {
						model.select([rec]);
						return;
					}
				});
			}	
		}, 200, this);
		//////////////////////contactGrid[用户列表] end///////////////////////
		
		///////////////////searchPanel[搜索面板] start//////////////////////
		this.searchPanel = new KE.SearchPanel({
			region : 'north',
			keys : {
				key : Ext.EventObject.ENTER,
				scope : this,
				fn : this.search
			},
			items : [{
					text : '用户姓名'
				}, {
					xtype : 'textfield',
					name : 'Q_fullname_S_LK',
					width : 260,
					maxLength : 256
				}, {
					xtype : 'button',
					text : '查询',
					scope : this,
					iconCls : 'btn-search',
					handler : this.search
				}, {
					xtype : 'button',
					text : '清空',
					scope : this,
					iconCls : 'reset',
					handler : this.reset
				}]
			}
		); // end of this searchPanel
		//////////////////////searchPanel[搜索面板] end//////////////////////////////////
		
		//////////////////////selectedUserGrid[已选用户列表] start/////////////////////
		this.selectedUserGrid = new KE.GridPanel({
			title : '已选用户',
			border : false,
			showPaging: false,
			isShowTbar: false,
			rownumbercfg: {
				width: 30
			},
			store : new Ext.data.ArrayStore({
    			fields : ['userId', 'fullname']
			}),
			columns : [{
				header : "姓名",
				dataIndex : 'fullname'
			}]
		}); 
		var me = this;
		this.selectedUserGrid.on('rowdblclick', function(grid, rec){
			var grid = me.selectedUserGrid;
			var store = grid.getStore();
			var rows = grid.getSelectionModel().getSelection();
			for(var i =0; i<rows.length; i++){
				store.remove(rows[i]);
			}
		});
		/////////////////////selectedUserGrid[已选用户列表] end //////////////
		this.contactGrid.on('rowdblclick', function(grid, rec){
			var selGrid = me.selectedUserGrid;
			var selStore = selGrid.getStore();
			var rows = me.contactGrid.getSelectionModel().getSelection();
			for(var i= 0 ; i<rows.length ; i++) {
				var userId = rows[i].data.userId;
				var fullname = rows[i].data.fullname;
				var isExist = false;
				//查找是否存在该记录
				for(var j=0;j<selStore.getCount();j++){
					if(selStore.getAt(j).data.userId == userId){
						isExist = true;
						break;
					}
				}
				if(!isExist){
					var newData = {userId : userId, fullname : fullname};
					var rec = selStore.getModel().create(newData);
					selStore.insert(selStore.getCount(), rec);
				}
			}
		});
		// 多选：根据传入值，选中GridPanel
		Ext.defer(function() {
			if(!isSingle && selval) {
				$postAjax({
					url : __ctxPath + '/system/selectedUserAppUser.do',
					params: {ids: selval},
					callback: function(json) {
						if(json.length > 0) {
							for(var i=0; i<json.length; i++) {
								var newData = {
									userId : json[i].userId,
									fullname : json[i].fullname
								};
								var selStore = me.selectedUserGrid.getStore(); 
								var rec = selStore.getModel().create(newData);
								selStore.insert(selStore.getCount(), rec);
							}
						}
					}
				});
			}	
		}, 300);		
		/////////////////////selectedPanel[多选面板] start/////////////////////
		//多选添加的面板
		this.selectedPanel = new Ext.Panel({
			layout : 'border',
			region : 'east',
			width : 260,
			height: 380,
			border : false,
			items : [new Ext.Panel({
				region : 'west',
				width : 50,
				layout : {
                    type : 'vbox',
                    pack : 'center',
                    align : 'stretch'
                },
                defaults: {
                	margin: '0 5 10 5',
                	xtype : 'button'
                },
                //defaultType : 'button',
                items : [{
                	iconCls : 'add-all',
                	text : '',
                	scope : this,
                	handler : this.addAll
                },{
                	iconCls : 'rem-all',
                	text : '',
                	scope : this,
                	handler : this.removeAll
                }]
			}), {
				region: 'center',
				layout: 'fit',
				items: [this.selectedUserGrid]
			}]
		}); // selectedPanel
		///////////////////////selectedPanel end//////////////////////////////
		
		/////////////////westPanel start///////////////////////
		this.westPanel = new Ext.Panel({
			layout : 'accordion',
			region : 'west',
			width : 200,
			split : true,
			header : false,
			collapsible : true,
			items : [this.treePanel, this.rolePanel, this.onlinePanel]
		}); // end of this westPanel
		/////////////////westPanel end///////////////////////
		
		var panel = new Ext.Panel({
			id : 'contactPanel',
			layout : 'border',
			border : false,
			anchor : '96%,96%',
			items : [this.searchPanel, this.westPanel, this.contactGrid]
		}); // end of this contactPanel
		//添加：多选面板
		if(isSingle != null && isSingle == false){
			panel.add(this.selectedPanel);
			panel.doLayout();
		}
		return panel;
	}, // init

	
	
	
	////////////////###方法###///////////////////////
	
	clickNode : function(view, node) {
		if (node != null) {
			var users = this.contactGrid;
			var store = users.getStore();
			store.proxy.url = __ctxPath + '/system/selectAppUser.do';
			store.proxy.extraParams = {
				depId : node.id
			};
			//从第1页开始加载
			store.reload({params: {start:0}});
		}
	},
	
	/**
	 * 角色查询用户信息
	 */
	clickRoleNode : function(view, node) {
		if (node != null) {
			var users = this.contactGrid;
			var store = users.getStore();
			store.proxy.extraParams = {
				roleId : node.id
			};
			store.proxy.url =__ctxPath + '/system/findAppUser.do';
			//从第1页开始加载
			store.reload({params: {start:0}});
		}
	},
	
	/**
	 * 在线用户
	 */
	clickOnlinePanel:function(){
		var users = this.contactGrid;
		var store = users.getStore();
		store.proxy.extraParams = {depId : null, roleId : null};
		store.proxy.url =__ctxPath + '/system/onlineAppUser.do';
		//从第1页开始加载
		store.reload({params: {start:0}});
	},
	
	/**
	 * 添加所有
	 */
	addAll : function(){
		var contactGrid = this.contactGrid;
		var selGrid = this.selectedUserGrid;
		var selStore = selGrid.getStore();
		var rows = contactGrid.getSelectionModel().getSelection();
		for(var i = 0; i<rows.length; i++) {
			var userId = rows[i].data.userId;
			var fullname = rows[i].data.fullname;
			var isExist = false;
			//查找是否存在该记录
			for(var j=0; j<selStore.getCount(); j++){
				if(selStore.getAt(j).data.userId== userId){
					isExist = true;
					break;
				}
			}
			if(!isExist){
				var newData = {userId:userId,fullname:fullname};
				var rec = selStore.getModel().create(newData);
				selStore.insert(selStore.getCount(), rec);
			}
		}
		selGrid.getView().refresh();
	},
	
	/**
	 * 移除所有
	 */
	removeAll : function(){
		var selGrid = this.selectedUserGrid;
		var rows = selGrid.getSelectionModel().getSelection();
		var selStore = selGrid.getStore();
		for(var i=0 ;i<rows.length; i++){
			selStore.remove(rows[i]);
		}
	},
	// 重置查询表单
	reset : function() {
		this.searchPanel.getForm().reset();
	},
	// 按条件搜索
	search : function() {
		$search({
				searchPanel : this.searchPanel,
				gridPanel : this.contactGrid
			});
	},
	
	/**
	 * 确定，提交
	 * @param isSingle 是否单选
	 * @param callback 回传函数
	 */
	submit : function(){
		var userIds = '';
		var fullnames = '';
		if(this.isSingle == null || this.isSingle){//选择单个用户
			var grid = this.contactGrid;
			var rows = grid.getSelectionModel().getSelection();
			
			for (var i = 0; i < rows.length; i++) {
				if (i > 0) {
					userIds += ',';
					fullnames += '，';
				}
				userIds += rows[i].data.userId;
				if(this.mobileFlag){
					fullnames += rows[i].data.fullname+'('+rows[i].data.mobile+')';
				}else{
					fullnames += rows[i].data.fullname;
				}
			}
		} else {
			var selStore = this.selectedUserGrid.getStore();
			for(var i = 0 ; i<selStore.getCount(); i++){
				if (i > 0) {
					userIds += ',';
					fullnames += '，';
				}
				userIds += selStore.getAt(i).data.userId;
				if(this.mobileFlag){
					fullnames += selStore.getAt(i).data.fullname+'('+selStore.getAt(i).data.mobile+')';
				}else{
					fullnames += selStore.getAt(i).data.fullname;
				}
			}
		}

		if (this.callback != null) {
			this.callback.call(this.scope, userIds, fullnames);
		}
		Ext.getCmp('UserSelectorWin').close();
	},
	
	/**
	 * 关闭当前窗口
	 */
	close : function(){
		Ext.getCmp('UserSelectorWin').close();
	}
};
